<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            :placeholder="$locale('jobList.Enter')"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :filter-node-method="filterNode"
            show-checkbox
            node-key="experimentId"
            :data="deptOptions"
            @check="handleCheckChange"
            :props="defaultProps"
            ref="tree"
          />
        </div>
      </el-col>
      <!--数据-->
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="120px"
        >
          <el-form-item :label="$locale('jobList.add.Student Name')" prop="studentName">
            <el-input
              v-model="queryParams.studentName"
              :placeholder="$locale('jobList.add.Please enter the student name')"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$locale('geWudevice.add.Experiment Name')" prop="experimentName">
            <el-input
              v-model="queryParams.experimentName"
              :placeholder="$locale('geWuExperiment.Please enter the experiment name')"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            >搜索
            </el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置
            </el-button
            >
          </el-form-item>
        </el-form>

        <el-table
          v-loading="loading"
          :data="teacherList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            :label="$locale('geWudevice.add.Experiment Name')"
            align="center"
            key="experimentName"
            prop="experimentName"
          >
          </el-table-column>
          <el-table-column
            :label="$locale('jobList.add.Student ID')"
            align="center"
            key="studentCode"
            prop="studentCode"
            width="160"
          >
          </el-table-column>
          <el-table-column
            :label="$locale('jobList.full name')"
            align="center"
            key="studentName"
            prop="studentName"
          >
          </el-table-column>
          <el-table-column
            :label="$locale('classList.class')"
            align="center"
            key="className"
            prop="className"
          >
          </el-table-column>
          <el-table-column
            width="150"
            sortable
            column-key="workStatus"
            :filters="filters"
            :label="$locale('jobList.job status')"
            align="center"
            key="status"
            prop="status"
          >
            <template slot-scope="scope">
              <span v-for="item in filters">
                {{ item.value == scope.row.workStatus ? item.text : '' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$locale('jobList.Team members')"
            align="center"
            key="teamNames"
            prop="teamNames"
          >
          </el-table-column>
          <el-table-column
            :label="$locale('jobList.Take photos before the experiment')"
            align="center"
            key="startExperimentPicture"
            prop="startExperimentPicture"
          >
            <template slot-scope="scope">
              <ImagePreview :src="scope.row.startExperimentPicture" />
            </template>
          </el-table-column>
          <el-table-column
            :label="$locale('jobList.Take photos after the experiment')"
            align="center"
            key="endExperimentPicture"
            prop="endExperimentPicture"
          >
            <template slot-scope="scope">
              <ImagePreview :src="scope.row.endExperimentPicture" />
            </template>
          </el-table-column>
          <el-table-column
            :label="$locale('jobList.Submission time')"
            align="center"
            key="submitDate"
            prop="submitDate"
          >
          </el-table-column>
          <el-table-column
            :label="$locale('jobList.Submit IP')"
            align="center"
            key="submitIP"
            prop="submitIP"
          >
          </el-table-column>
          <el-table-column
            :label="$locale('jobList.fraction')"
            align="center"
            key="experimentFraction"
            prop="experimentFraction"
          >
          </el-table-column>
          <el-table-column
            :label="$locale('formMarkering.list.operate')"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleGuidebook(scope.row)"
              >{{ $locale('formMarkering.list.Guidebook') }}
              </el-button
              >
              <el-button
                type="text"
                size="mini"
                @click="handleReturn(scope.row)"
              >{{ $locale('jobList.return') }}
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加 -->
    <add ref="jobListAdd" @getList="getList"></add>
    <import-table :import-url="'/minio/upload'" ref="import" @ok="getList" />
    <el-dialog :visible.sync="guidebookVisible" :title="$locale('jobList.Guidebook evaluation')" :show-close="false" fullscreen destroy-on-close>
      <guidebook-score ref="refGuidebookScore" :work-id="guidebookId" />
      <template #footer>
        <el-button type="primary" @click="handleSubmit">{{ $locale('jobList.Judgment completed') }}</el-button>
        <el-button @click="handleCancel">{{ $locale('formMarkering.list.tip4') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { classExperiment, deleteById, list, setStatus, setStatusByIds } from '@/api/myClass/jobList';
import importTable from '@/components/ImportTemplate/index.vue';
import { getNames } from '@/utils/index';
import add from './add/index.vue';
import guidebookScore from './components/score/index.vue'

export default {
  name: 'jobList',
  dicts: ['data_status'],
  components: { add, importTable, guidebookScore },
  data() {
    return {
      // 遮罩层
      loading: true,
      filters: [
        { text: this.$locale('jobList.not submitted'), value: '0' },
        { text: this.$locale('jobList.submitted'), value: '1' },
        { text: this.$locale('jobList.Uncorrected'), value: '2' },
        { text: this.$locale('jobList.Corrected'), value: '3' }
      ],
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      teacherList: [],
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 表单参数
      defaultProps: {
        children: 'experimentVOS',
        label: 'experimentName'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: '',
        experimentName: ''
      },
      guidebookVisible: false,
      guidebookId: ''
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    handleCancel() {
      this.guidebookVisible = false
    },
    handleSubmit() {
      this.$refs.refGuidebookScore.$submit().then(() => {
        this.getList()
        this.guidebookVisible = false
      })
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      list(this.queryParams).then(({ data }) => {
        this.teacherList = data.records;
        this.total = data.total;
        this.loading = false;
      });
    },
    filterHandler(value, row, column) {
      const property = column['property'];
      return row[property] == value;
    },
    /** 打开导入表弹窗 */
    openImportTable() {
      this.$refs.import.show();
    },
    // 处理选中状态变化
    handleCheckChange(node, checked, indeterminate) {
      const filteredExperimentIds = this.$refs.tree
        .getCheckedNodes(true)
        .filter((item) => {
          const experimentId = item.experimentId;

          // 如果 experimentId 是字符串，尝试解析 JSON 对象
          if (typeof experimentId === 'string') {
            try {
              const parsedId = JSON.parse(experimentId);
              // 如果解析成功且 parsedId 是对象，则检查是否包含 'father'
              return typeof parsedId !== 'object' || !parsedId.father;
            } catch {
              // 如果解析失败，直接判断是否包含 'father'
              return !experimentId.includes('father');
            }
          }

          // 如果 experimentId 不是字符串，直接返回 true（假设是有效的）
          return true;
        })
        .map((item) => item.experimentId);
      this.queryParams.experimentIds = filteredExperimentIds;
      this.getList();
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      return new Promise((resolve, reject) => {
        classExperiment()
          .then((response) => {
            this.deptOptions = response.data.map((item) => {
              item['experimentName'] = item.className;
              item['experimentId'] = 'father' + item.classId;
              return item;
            });
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    /** 修改按钮操作 */
    handleResetting(row) {
      this.resetForm('form');
      this.open = true;
    },
    handleExperiment() {
    },
    getDeptTreeClass(node) {
      return new Promise((resolve, reject) => {
        classExperiment({ name: node.data.name })
          .then((response) => {
            let data = response.data[0]['experimentVOS'].map((item) => {
              item['name'] = item.experimentName;
              item['id'] = item.experimentId;
              item['leaf'] = true;
              return item;
            });
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    handleGuidebook(row) {
      this.guidebookId = row['guidebookId']
      this.guidebookVisible = true
    },
    handleReturn() {
    },
    /** 冻结按钮操作 */
    handleFreeze(row) {
      const Ids = (row && row.id) || this.ids;
      this.$modal
        .confirm(
          this.$locale('geWudevice.tip4') +
          getNames(this.teacherList, Ids, 'experimentName') +
          this.$locale('geWudevice.tip2')
        )
        .then(() => {
          if (row && row.id) {
            setStatus({ id: Ids }).then(() => this.getList());
          } else {
            setStatusByIds({ id: Ids }).then(() => this.getList());
          }
        })
        .then((res) => {
          if (res.code == 200) this.$modal.msgSuccess(this.$locale('geWudevice.tip5'));
        })
        .catch(() => {
        });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.experimentName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.experimentId = undefined;
      this.queryParams.classId = undefined;
      if (data.classId) {
        this.queryParams.classId = data.classId;
        this.handleQuery();
      } else {
        this.queryParams.experimentIds = [data.experimentId];
        this.handleQuery();
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.tree.setCheckedKeys([]);
      this.resetForm('queryForm');
      this.queryParams.experimentIds = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleBatch() {
      list({ id: this.ids }).then(({ data }) => {
        this.$modal.msgSuccess(this.$locale('jobList.Batch success'));
      });
    },
    /** 报价按钮操作 */
    handleQuotation(row, disabled) {
      this.$refs.jobListAdd.handleUpdate(row, disabled);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id || this.ids;
      this.$modal
        .confirm(
          this.$locale('geWudevice.tip1') +
          getNames(this.teacherList, Ids, 'experimentName') +
          this.$locale('geWudevice.tip2')
        )
        .then(function() {
          return deleteById({ id: Ids });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$locale('geWudevice.tip3'));
        })
        .catch(() => {
        });
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    }
  }
};
</script>
<style lang="scss">
::v-deep .el-table__row--level-1 .el-checkbox {
  display: none;
}

.el-dialog__body {
  height: calc(100% - 120px);
}
</style>
